package com.sky.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper disMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    StemealDishMapper stemealDishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    /**
     * 新增菜品
     * 保存菜品和口味信息
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveDishAndFlavor(DishDTO dishDTO) {
        //1、保存菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //注意：应该返回主键
        disMapper.save(dish);
        //2、保存口味
        //注意：存口味是需要和菜品的id绑定
        //获取菜品的id
        //需要给每个口味设置口味id
        List<DishFlavor> flavorList = dishDTO.getFlavors()
                .stream()
                .map(dishFlavor -> {
                    dishFlavor.setDishId(dish.getId());
                    return dishFlavor;

                }).collect(Collectors.toList());
        dishFlavorMapper.saveFlavoies(flavorList);

    }


    /**
     * 菜品分页
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<Dish> list = disMapper.page(dishPageQueryDTO);
        PageInfo<Dish> pageInfo = new PageInfo<>(list);

        //把list缓存DishVo的list
        List<DishVO> voList = list.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);

            Category category = categoryMapper.findById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());
            return dishVO;
        }).collect(Collectors.toList());

        return new PageResult(pageInfo.getTotal(), voList);
    }


    /**
     * 根据id删除一条或者多条
     *
     * @param ids 什么情况下不能删除
     *            1、菜品启用的时候
     *            2、判断是否菜品是否关联了套餐
     *            <p>
     *            <p>
     *            核心逻辑
     *            根据id删除
     *            根据dishid删除口味
     */
    @Transactional
    @Override
    public void delByIds(List<Long> ids) {
        //1、根据id查询菜品，判断状态
        ids.forEach(id -> {
            //根据id查询菜品
            Dish dish = disMapper.findById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2.判断菜品是否关联了套餐（可能有多个菜品）
        List<Long> setmealIds = stemealDishMapper.findSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //根据id删除菜品
        disMapper.delByids(ids);

        //根据dishid删除口味
        ids.forEach(id -> {
            dishFlavorMapper.delDishByid(id);
        });
    }


    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findById(Long id) {
        Dish dish = disMapper.findById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        List<DishFlavor> dishId = dishFlavorMapper.findByDishId(dish.getId());
        dishVO.setFlavors(dishId);
        return dishVO;
    }


    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Override
    public Result update(DishDTO dishDTO) {
        ArrayList<Long> list = new ArrayList<>();
        list.add(dishDTO.getId());
        for (Long ids : list) {
            dishFlavorMapper.delDishByid(ids);
        }

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        disMapper.update(dish);

        if (dishDTO.getFlavors().size() == 0) {
            return Result.success();
        }

        List<DishFlavor> flavorList = dishDTO.getFlavors()
                .stream()
                .map(dishFlavor -> {
                    dishFlavor.setDishId(dish.getId());
                    return dishFlavor;
                }).collect(Collectors.toList());


        dishFlavorMapper.saveFlavoies(flavorList);
        return Result.success();
    }


    /**
     * 启用或者禁用
     *
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void enableOrDisable(Integer status, Long id) {
        Dish dish = Dish.builder().id(id).status(status).build();
        disMapper.update(dish);
        if (status == StatusConstant.DISABLE) {
            SetmealDish setmealDish = stemealDishMapper.findBydishId(id);

            if(setmealDish==null){
                return;
            }
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(StatusConstant.DISABLE);
            setmeal.setId(setmealDish.getSetmealId());
            setmealMapper.update(setmeal);
        }

    }

    /**
     * 根据id分类查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public List<Dish> findByCategoryId(Long id) {
        List<Dish> list = disMapper.findByCategoryId(id);
        return list;
    }

    /**
     * 条件查询菜品和口味
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(DishDTO dishDTO) {
        List<Dish> dishList = disMapper.findDishesByCid(dishDTO);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.findByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
